//
//  AppDelegate.m
//  MeiXin
//
//  Created by 史宵宵 on 2017/5/27.
//  Copyright © 2017年 史宵宵. All rights reserved.
//  com.meixin.zy.AndCampus

#import "AppDelegate.h"
#import "YJTabBarController.h"
#import "TBCityIconFont.h"
#import "GuideViewController.h"
#import "FriendCircleViewController.h"
#import "ClassRoomViewController.h"
#import "WXApi.h"
#import <AlipaySDK/AlipaySDK.h>

//// 引入JPush功能所需头文件
//#import "JPUSHService.h"
//// iOS10注册APNs所需头文件
//#ifdef NSFoundationVersionNumber_iOS_9_x_Max
//#import <UserNotifications/UserNotifications.h>
//#endif
//// 如果需要使用idfa功能所需要引入的头文件（可选）
//#import <AdSupport/AdSupport.h>
#import <AVFoundation/AVFoundation.h>

@interface AppDelegate ()<UITabBarControllerDelegate,WXApiDelegate>
//启动页view
@property (strong, nonatomic) UIView *LaunchView;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
//    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    //创建window
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
//
    //获取启动页
//    UIStoryboard *LaunchScreen = [UIStoryboard storyboardWithName:@"LaunchScreen" bundle:nil];
    //这一步是获取LaunchScreen.storyboard里的UIViewController,UIViewController 的identifer是LaunchScreen
//    UIViewController *viewController = [[UIStoryboard storyboardWithName:@"LaunchScreen" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"LaunchScreen"];
//    UIView *launchView = viewController.view;
//    [self.view addSubview:launchView];
    
    
//    self.LaunchView = viewController.view;
    
    //加载启动页
    
    [self applicationShowGuide];
    [self.window makeKeyAndVisible];
    
    [WXApi registerApp:WXAPPID];
    [TBCityIconFont setFontName:@"iconfont"];
//    [self getHomePage];

    
    
    //锁屏继续播放
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    //默认情况下扬声器播放
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES error:nil];
    
    return YES;
}
- (void)applicationShowGuide    //加载引导页
{
    [NSThread sleepForTimeInterval:2.0]; //延时2秒，以便用户看清楚启动页
    
    NSString *guideVersion=[[NSUserDefaults standardUserDefaults] objectForKey:GUIDE_VERSION];
    if (![guideVersion isEqualToString:IOSSHORTAPPVERSION])
    {
        [UIApplication sharedApplication].statusBarHidden = YES;
        //首次安装显示引导
        GuideViewController *guideViewController = [[GuideViewController alloc] init];
        self.window.rootViewController = guideViewController;
    }
    else
    {
        [self applicationLaunched];
    }
}

-(void)applicationLaunched  //加载广告页
{
    [self enterTheMainViewIndex:0];
//    [self getHomePage];
}

- (void)enterTheMainViewIndex:(NSInteger)index{
   
    YJTabBarController *tabbarVC=[[YJTabBarController alloc]init];
    tabbarVC.delegate=self;
    
    tabbarVC.selectedIndex = index;
    self.window.rootViewController = tabbarVC;
}
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    UINavigationController *navC = (UINavigationController *)viewController;
    MyLog(@"___%@,%lu",navC.topViewController,(unsigned long)tabBarController.selectedIndex);
//    if ([[JHUserInfo getUserInfo].role_type isEqualToString:@"6"] && ([navC.topViewController isKindOfClass:[FriendCircleViewController class]] || [navC.topViewController isKindOfClass:[ClassRoomViewController class]])) {
//        [Global showActivityWithView:[[UIApplication sharedApplication] keyWindow] withText:@"该功能只针对与时老师和本校老师"];
//        return NO;
//    }
    return YES;
}
- (void)getHomePage{
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:@"1" forKey:@"page"];   //
    [dic setValue:@"1" forKey:@"rows"];   //每页数量
    [dic setValue:@"2" forKey:@"businessType"];   //业务类型
    [yjNetWorkManger requestType:POST andURL:[JSPathUtil urlAppHomePageGetHomePage] andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            /*
             
             */
            NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:response[@"list"][0]];
//                        [dic setObject:code forKey:@"code"];
            MyLog(@"%@",dic[@"pathUrl"]);
            //异步加载图片
            dispatch_queue_t queue = dispatch_queue_create("loadImage", NULL);
            dispatch_async(queue, ^{
    
                //图片资源
                NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:dic[@"pathUrl"]]];
                UIImage *img = [UIImage imageWithData:imgData];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    //创建imageView
                    UIImageView *adView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height)];
                    adView.image = img;
//                    adView.backgroundColor = [UIColor yellowColor];
//                    [adView sd_setImageWithURL:dic[@"pathUrl"]];
                    
                    //添加图片点击手势
                    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickAD)];
                    adView.userInteractionEnabled = YES;
                    [adView addGestureRecognizer:singleTap];
                    
                    [self.LaunchView addSubview:adView];
                    
                    //LaunchView前置于window
                    [self.window bringSubviewToFront:self.LaunchView];
                    
                    //延迟5秒后删除广告
                    [self performSelector:@selector(removeAd) withObject:nil afterDelay:5];
                });
            });
        }
    }];
}
#pragma mark 广告点击
- (void)clickAD {
    [self removeAd];
}

#pragma mark 删除广告
- (void)removeAd
{
    [self.LaunchView removeFromSuperview];
    

    [self enterTheMainViewIndex:0];
    
}
-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
    MyLog(@"-------------------------------%@",url.scheme);
    if([url.scheme isEqualToString:WXAPPID])
    {
        MyLog(@"---------------------筑云客户微信号+++++++++++++++++回调");
        return [WXApi handleOpenURL:url delegate:self];
    }else if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            if ([[NSString stringWithFormat:@"%@",resultDic[@"resultStatus"]] isEqualToString:@"9000"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"AlipayPaySuccess" object:nil];
                MyLog(@"支付成功");
            }
            MyLog(@"result ===== %@",resultDic);
        }];
    }
    
    
    return YES;
}
-(void)onResp:(BaseResp*)resp{
    if ([resp isKindOfClass:[PayResp class]]){
        PayResp*response=(PayResp*)resp;
        switch(response.errCode){
            case WXSuccess: //服务器端查询支付通知或查询API返回的结果再提示成功
                [[NSNotificationCenter defaultCenter] postNotificationName:@"WeiXinPaySuccess" object:nil];
                 MyLog(@"支付成功");
                 break;
            default:
                 MyLog(@"支付失败，retcode=%d",resp.errCode);
                 break;
        }
    }
}
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            if ([[NSString stringWithFormat:@"%@",resultDic[@"resultStatus"]] isEqualToString:@"9000"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"AlipayPaySuccess" object:nil];
                MyLog(@"支付成功");
            }
            MyLog(@"result ====== %@",resultDic);
        }];
    }
    return YES;
}

/*
 result = "{"alipay_trade_app_pay_response":{"code":"10000","msg":"Success","app_id":"2018011401854871","auth_app_id":"2018011401854871","charset":"utf-8","timestamp":"2018-02-02 18:09:06","total_amount":"0.01","trade_no":"2018020221001004010518674207","seller_id":"2088921298312274","out_trade_no":"18020218073500000023"},"sign":"bsI36kKnxHpvdgQmOR3FYK0dy4bLCz1ll76WR2SvoZqtnVQjTJ/oLumrtClmVrgyw/FJ2mjKceIcoGwXixfA8KfeQejssjhIoLHQ+jcOCds+ZcwB6dfzio+D7f8QhAPIdOhNXp7ha/1uH179Kfjbl5NHLoYG5yanbaR8bwfoobbCFirx2z4nueD77V21gVSMgwNuDeCgDM1AK4wETBnkZng2IWf+Bpwvg0pdv/FgzDuMnZ9Ui60PWDZarikOu+qhVeEqzmVVU4GYEyaIkP5sDl2t7zarMIMwfu4GCVkXjBv4iEPXApjQECUyWkV/Mv5j6n1qYpwBVGnQcz/O16VE1Q==","sign_type":"RSA2"}",
 resultStatus = "9000",
 memo = "",
 */
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

//-(void)applicationWillResignActive:(UIApplication *)application
//{
//    //开启后台处理多媒体事件
//    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
////    AVAudioSession *session=[AVAudioSession sharedInstance];
////    [session setActive:YES error:nil];
////    //后台播放
////    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
////    //这样做，可以在按home键进入后台后 ，播放一段时间，几分钟吧。但是不能持续播放网络歌曲，若需要持续播放网络歌曲，还需要申请后台任务id，具体做法是：
////    _bgTaskId=[AppDelegate backgroundPlayerID:_bgTaskId];
////    //其中的_bgTaskId是后台任务UIBackgroundTaskIdentifier _bgTaskId;
//}
//+(UIBackgroundTaskIdentifier)backgroundPlayerID:(UIBackgroundTaskIdentifier)backTaskId
//{
//    //设置并激活音频会话类别
//    AVAudioSession *session=[AVAudioSession sharedInstance];
//    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
//    [session setActive:YES error:nil];
//    //允许应用程序接收远程控制
//    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
//    //设置后台任务ID
//    UIBackgroundTaskIdentifier newTaskId=UIBackgroundTaskInvalid;
//    newTaskId=[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
//    if(newTaskId!=UIBackgroundTaskInvalid&&backTaskId!=UIBackgroundTaskInvalid)
//    {
//        [[UIApplication sharedApplication] endBackgroundTask:backTaskId];
//    }
//    return newTaskId;
//}
@end
